/**
 * Web兼容的Alert工具
 */

import { Platform, Alert } from 'react-native';

interface AlertButton {
  text: string;
  onPress?: () => void;
  style?: 'default' | 'cancel' | 'destructive';
}

// Web端的Alert实现
const webAlert = (title: string, message?: string, buttons?: AlertButton[]) => {
  if (Platform.OS === 'web') {
    // 在Web端使用浏览器的alert和confirm
    if (buttons && buttons.length > 1) {
      // 如果有多个按钮，使用confirm
      const result = window.confirm(`${title}\n\n${message || ''}`);
      if (result && buttons[1]?.onPress) {
        buttons[1].onPress();
      } else if (!result && buttons[0]?.onPress) {
        buttons[0].onPress();
      }
    } else {
      // 单个按钮或无按钮，使用alert
      window.alert(`${title}\n\n${message || ''}`);
      if (buttons && buttons[0]?.onPress) {
        buttons[0].onPress();
      }
    }
  } else {
    // 移动端使用原生Alert
    Alert.alert(title, message, buttons);
  }
};

// 成功提示
export const showSuccess = (message: string, onPress?: () => void) => {
  webAlert('成功', message, [
    {
      text: '確定',
      onPress,
    },
  ]);
};

// 错误提示
export const showError = (message: string, onPress?: () => void) => {
  webAlert('錯誤', message, [
    {
      text: '確定',
      onPress,
    },
  ]);
};

// 确认对话框
export const showConfirm = (
  title: string,
  message: string,
  onConfirm: () => void,
  onCancel?: () => void
) => {
  webAlert(title, message, [
    {
      text: '取消',
      style: 'cancel',
      onPress: onCancel,
    },
    {
      text: '確定',
      onPress: onConfirm,
    },
  ]);
};

export default webAlert;
